package com.globallogic.jira.gadget.utils;

/**
 * A object that used to build form with several fields. Note, that it will
 * become immutable when you call {@link #getForm()} method.
 * 
 * @author anton.pereverziev
 * @author yegor.chumakov
 */

public final class FormBuilder {
	private final StringBuilder builder = new StringBuilder();
	private boolean finished = false;

	public FormBuilder(final String action) {
		builder.append("<div id=\"dialog_request\" title=\"Dialog\">")
				.append("<form id=\"dialog\">")
				.append("<input type=hidden name=\"action\" value=\"")
				.append(action).append("\">")
				.append("<table class=\"dialog_table\">");
	}

	/**
	 * Adds a field with specific name and input type
	 * 
	 * @param name
	 * @param input
	 */
	public FormBuilder addField(final String name, final String input) {
		if (!finished) {
			builder.append("<tr>")
					.append("<td class=\"dialog_table_column_text\">")
					.append(name).append("</td>")
					.append("<td class=\"dialog_table_column_input\">")
					.append(input).append("</td>").append("</tr>");
		}
		return this;
	}

	/**
	 * Finish the creation of form, object will become immutable, so
	 * <tt>addField</tt> will cause no effect.
	 * 
	 * @return
	 */
	public String getForm() {
		if (!finished) {
			builder.append("</table>").append("</form>").append("</div>");
			finished = true;
		}
		return builder.toString();
	}
}
